<template>
  <div class="container">
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">邮箱地址</label>
        <validate-input :rules="emailRules" v-model="emailVal" placeholder="请输入邮箱地址" type="text" ref="inputRef">
        </validate-input>
      </div>
      <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">密码</label>
        <validate-input class="form-control" id="exampleInputPassword1" placeholder="请输入密码" type="password"
          :rules="passwordRules" v-model="passwordVal" />
      </div>
    </ValidateForm>
    <router-view />
  </div>
</template>
<script lang="ts" setup>
import "bootstrap/dist/css/bootstrap.min.css";
import { ref } from "vue";
import ValidateInput, { RulesProp } from "@/components/ValidateInput.vue";
import createMessage from "@/components/createMessage";
import ValidateForm from "@/components/ValidateForm.vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const store = useStore();

const router = useRouter();

// input 的ref，用来获取dom
const inputRef = ref("");
// 邮箱
const emailVal = ref("");
// 密码
const passwordVal = ref("");

// 邮箱正则
const emailRules: RulesProp = [
  { type: "required", message: "邮箱不能为空" },
  { type: "email", message: "邮箱格式不正确" },
];

const passwordRules: RulesProp = [
  {
    type: "required",
    message: "密码不能为空",
  },
];

// 表单提交事件
const onFormSubmit = (result: boolean) => {
  if (result) {

    const payload = {
      email: emailVal.value,
      password: passwordVal.value
    }

    store.dispatch('login', payload).then(res => {
      // 把用户信息存缓存
      localStorage.setItem('user', JSON.stringify(res))
      createMessage('登陆成功，2秒后跳转首页', 'success')
      setTimeout(() => {
        router.push("/");
      }, 2000);
    }).catch(e => {
      console.log(e);
    })

    // 提交成功，清空表单
    // emailVal.value = "";
    // passwordVal.value = "";
  }
};
</script>
<style lang="scss">
</style>
